using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.WebSockets;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Media.Imaging;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Config;
using IMClient.Model;
using IMClient.Model.DTO;
using IMClient.View;
using IMClient.WebSocketService;
using Microsoft.Win32;
using Newtonsoft.Json.Linq;

namespace IMClient.ViewModels
{
    public partial class RegisterViewModel : ObservableObject
    {
        [ObservableProperty] private string userName = string.Empty;

        [ObservableProperty] private string password = string.Empty;

        [ObservableProperty] private string avatarPath = string.Empty;

        [ObservableProperty] private BitmapImage avatarImage =
            new BitmapImage(new Uri("https://im-net.oss-cn-wuhan-lr.aliyuncs.com/default.png"));

        [ObservableProperty] private string? userNameError;

        [ObservableProperty] private string? passwordError;

        [ObservableProperty] private bool hasUserNameError;

        [ObservableProperty] private bool hasPasswordError;

        [RelayCommand]
        private void SelectAvatar()
        {
            var openFileDialog = new OpenFileDialog
            {
                Filter = "Image Files (*.png;*.jpg;*.jpeg)|*.png;*.jpg;*.jpeg|All Files (*.*)|*.*",
                RestoreDirectory = true,
                Title = "请选择头像"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                AvatarPath = openFileDialog.FileName;
                AvatarImage = new BitmapImage(new Uri(AvatarPath));
            }
        }

        [RelayCommand]
        private async Task Register()
        {
            ResetErrors();

            if (!ValidateInput())
                return;

            try
            {
                using var httpClient = new HttpClient();
                using var formData = new MultipartFormDataContent();
                formData.Add(new StringContent(UserName), "UserName");
                formData.Add(new StringContent(Password), "Password");

                if (!string.IsNullOrEmpty(AvatarPath))
                {
                    var avatarBytes = await File.ReadAllBytesAsync(AvatarPath);
                    var avatarContent = new ByteArrayContent(avatarBytes);
                    avatarContent.Headers.ContentType =
                        new MediaTypeHeaderValue("image/jpeg");
                    formData.Add(avatarContent, "Avatar", Path.GetFileName(AvatarPath));
                }

                var response = await httpClient.PostAsync($"{NetWorkConfig.BaseUrl}/user/auth/register", formData);

                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();

                    // 解析 JSON
                    var jsonObject = JObject.Parse(json);
                    
                    string userId = jsonObject["data"]?["userId"]?.ToString() ?? String.Empty;
                    string userName = jsonObject["data"]?["userName"]?.ToString() ?? String.Empty;
                    string avatar = jsonObject["data"]?["avatar"]?.ToString() ?? String.Empty;
                    string webSocketUrl = jsonObject["data"]?["webSocketUrl"]?.ToString() ?? String.Empty;
                        
                    User.UserAvatar = !string.IsNullOrEmpty(avatar) ? avatar : // 将 avatar 字段赋值
                        "https://im-net.oss-cn-wuhan-lr.aliyuncs.com/default.png";

                    User.UserId = userId;
                    User.UserName = userName;
                    User.FriendList = new List<FriendDto>();
                    User.GroupList = new List<GroupDto>();
                    WebSocketConnection.WebSocketUrl = webSocketUrl;
                    
                    if (WebSocketConnection.WS == null || WebSocketConnection.WS.State != WebSocketState.Open)
                    {
                        await WebSocketConnection.ConnectWebSocket();
                    }

                    // 启动消息接收任务
                    WebSocketConnection.StartReceivingMessages();
                    
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        ChatWindow chatWindow = new ChatWindow();
                        chatWindow.Show();
                        
                        // 关闭所有RegisterWindow类型的窗口
                        foreach (Window window in Application.Current.Windows.Cast<Window>().ToList())
                        {
                            if (window.GetType().Name == "RegisterWindow")
                            {
                                window.Close();
                            }
                        }
                        
                        // 设置新窗口为主窗口
                        Application.Current.MainWindow = chatWindow;
                    });
                }
                else
                {
                    MessageBox.Show($"注册失败：{response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误：{ex.Message}");
            }
        }

        private bool ValidateInput()
        {
            bool isValid = true;

            // 用户名验证：只能包含中文字符、数字、英文字母和下划线
            if (string.IsNullOrEmpty(UserName))
            {
                UserNameError = "用户名不能为空";
                HasUserNameError = true;
                isValid = false;
            }
            else if (!Regex.IsMatch(UserName, @"^[\u4e00-\u9fa5a-zA-Z0-9_]+$"))
            {
                UserNameError = "用户名只能包含中文、字母、数字和下划线";
                HasUserNameError = true;
                isValid = false;
            }

            // 密码验证：只能包含数字和英文字母
            if (string.IsNullOrEmpty(Password))
            {
                PasswordError = "密码不能为空";
                HasPasswordError = true;
                isValid = false;
            }
            else if (Password.Length < 6 || Password.Length > 20)
            {
                PasswordError = "密码长度必须在6-20个字符之间";
                HasPasswordError = true;
                isValid = false;
            }
            else if (!Regex.IsMatch(Password, @"^[a-zA-Z0-9]+$"))
            {
                PasswordError = "密码只能包含字母和数字";
                HasPasswordError = true;
                isValid = false;
            }

            return isValid;
        }

        private void ResetErrors()
        {
            HasUserNameError = false;
            HasPasswordError = false;
            UserNameError = string.Empty;
            PasswordError = string.Empty;
        }
    }
}